/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.vng.zing.zprofilefrontend.model;

import com.vng.zing.zprofilefrontend.common.Util;
import com.vng.zing.zprofilefrontend.common.Validation;
import com.vng.zing.calc.thrift.Profile;
import com.vng.zing.calc.thrift.ProfileSession;
import com.vng.zing.logger.ZLogger;
import com.vng.zing.stats.Profiler;
import com.vng.zing.stats.ThreadProfiler;
import com.vng.zing.zcommon.thrift.PutPolicy;
import static com.vng.zing.zprofilefrontend.model.BaseModel.checkLogIn;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;

/**
 *
 * @author namhh
 */
public class AjaxLogInModel extends BaseModel {

    private static final Logger _Logger = ZLogger.getLogger(LogInModel.class);
    public static final AjaxLogInModel Instance = new AjaxLogInModel();

    @Override
    public void process(HttpServletRequest req, HttpServletResponse resp) {
        ThreadProfiler profiler = Profiler.getThreadProfiler();
        resp.setContentType("text/html; charset=UTF-8");
        PrintWriter out = null;
        try {
            out = resp.getWriter();
            profiler.push(this.getClass(), "output");
             ProfileSession profileSession = checkLogIn(req);
            if (null != checkLogIn(req)) {
                out.println(Util.toJSON("SUCCESS", "/info?id=" + profileSession.getId()));
            } else {
                if (null == req.getParameter("username") || null == req.getParameter("password")) {
                    out.println(Util.toJSON("ERROR", getProperties().get("en.INVALID_USERNAME") +  getProperties().get("en.INVALID_PASSWORD")));
                } else {
                    String username = req.getParameter("username");
                    String password = req.getParameter("password");
                    boolean isRemember = Boolean.parseBoolean(req.getParameter("isRemember"));
                    String error = validateLogIn(username, password);
                    if ("".equals(error)) {
                        Profile profile = getClient().logIn(username, password);
                        if (null != profile) {
                            getClientWithCache().putCache(profile.getId(), profile, PutPolicy.ADD_OR_UDP);
                            setLoggedIn(req, resp, new ProfileSession(profile.getId()), isRemember);
                            out.println(Util.toJSON("SUCCESS", "/info?id=" + profile.getId()));
                        } else {
                            out.println(Util.toJSON("ERROR", getProperties().get("en.login.invalidUsernamePassword")));
                        }
                    } else {
                        out.println(Util.toJSON("ERROR", getProperties().get("en.login.invalidUsernamePassword")));
                    }
                }
            }
            profiler.pop(this.getClass(), "output");
        } catch (Exception ex) {
            _Logger.error(null, ex);
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }

    private  String validateLogIn(String username, String password) {
        String message = "";

        if (!Validation.validateUsername(username)) {
            message += getProperties().get("en.INVALID_USERNAME");
        }

        if (!Validation.validatePassword(password)) {

            message += getProperties().get("en.INVALID_PASSWORD");
        }

        return message;
    }

}
